<template>
  <el-dialog
    :title="isEdit ? '编辑机房' : '添加机房'"
    v-model="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    align-center
    @close="handleClose"
  >
    <el-steps :active="activeStep" finish-status="success" class="form-steps">
      <el-step title="位置环境"> </el-step>
      <el-step title="基础参数"> </el-step>
      <el-step title="联系信息"> </el-step>
    </el-steps>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="140px"
      label-position="left"
      class="room-form"
      status-icon
    >
      <!-- 步骤1：位置环境 -->
      <div v-show="activeStep === 0">
        <div class="form-row">
          <el-form-item label="机房名称" prop="room_name">
            <template #label><span>机房名称</span></template>
            <el-input v-model="form.room_name" placeholder="请输入机房名称" />
          </el-form-item>
          <el-form-item label="位置" prop="location">
            <template #label><span>位置</span></template>
            <el-input v-model="form.location" placeholder="请输入机房位置" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="建筑名称" prop="building_name">
            <template #label><span>建筑名称</span></template>
            <el-input v-model="form.building_name" placeholder="请输入建筑名称" />
          </el-form-item>
          <el-form-item label="楼层" prop="floor_number">
            <template #label><span>楼层</span></template>
            <el-input-number
              v-model="form.floor_number"
              :min="0"
              :step="1"
              :controls="false"
              class="number-input"
              placeholder="请输入楼层"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="温度(°C)" prop="temperature">
            <template #label><span>温度(°C)</span></template>
            <el-input-number
              v-model="form.temperature"
              :min="0"
              :precision="1"
              :step="0.5"
              :controls="false"
              class="number-input"
            />
          </el-form-item>
          <el-form-item label="湿度(%)" prop="humidity">
            <template #label><span>湿度(%)</span></template>
            <el-input-number
              v-model="form.humidity"
              :min="0"
              :max="100"
              :precision="1"
              :step="1"
              :controls="false"
              class="number-input"
            />
          </el-form-item>
        </div>
      </div>

      <!-- 步骤2：基础参数 -->
      <div v-show="activeStep === 1">
        <div class="form-row">
          <el-form-item label="状态" prop="status">
            <template #label><span>状态</span></template>
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="正常" value="正常" />
              <el-option label="维护中" value="维护中" />
              <el-option label="停用" value="停用" />
            </el-select>
          </el-form-item>
          <el-form-item label="额定功率(kW)" prop="power_capacity">
            <template #label><span>额定功率(kW)</span></template>
            <el-input-number
              v-model="form.power_capacity"
              :min="0"
              :precision="2"
              :step="100"
              :controls="false"
              class="number-input"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="制冷能力(kW)" prop="cooling_capacity">
            <template #label><span>制冷能力(kW)</span></template>
            <el-input-number
              v-model="form.cooling_capacity"
              :min="0"
              :precision="2"
              :step="100"
              :controls="false"
              class="number-input"
            />
          </el-form-item>
          <el-form-item label="机柜容量" prop="cabinet_capacity">
            <template #label><span>机柜容量</span></template>
            <el-input-number
              v-model="form.cabinet_capacity"
              :min="0"
              :step="1"
              :controls="false"
              class="number-input"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="可用机柜数" prop="available_cabinets">
            <template #label><span>可用机柜数</span></template>
            <el-input-number
              v-model="form.available_cabinets"
              :min="0"
              :step="1"
              :controls="false"
              class="number-input"
            />
          </el-form-item>
        </div>
      </div>

      <!-- 步骤3：联系信息 -->
      <div v-show="activeStep === 2">
        <div class="form-row">
          <el-form-item label="维护联系人" prop="maintenance_contact">
            <template #label><span>维护联系人</span></template>
            <el-input v-model="form.maintenance_contact" placeholder="请输入维护联系人" />
          </el-form-item>
          <el-form-item label="维护电话" prop="maintenance_phone">
            <template #label><span>维护电话</span></template>
            <el-input v-model="form.maintenance_phone" placeholder="请输入维护电话" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="紧急联系人" prop="emergency_contact">
            <template #label><span>紧急联系人</span></template>
            <el-input v-model="form.emergency_contact" placeholder="请输入紧急联系人" />
          </el-form-item>
          <el-form-item label="紧急电话" prop="emergency_phone">
            <template #label><span>紧急电话</span></template>
            <el-input v-model="form.emergency_phone" placeholder="请输入紧急电话" />
          </el-form-item>
        </div>

        <el-form-item label="备注" prop="notes">
          <template #label><span>备注</span></template>
          <el-input v-model="form.notes" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handlePrev" v-if="activeStep > 0">上一步</el-button>
        <el-button type="primary" @click="handleNext" v-if="activeStep < 2">下一步</el-button>
        <el-button @click="dialogVisible = false" v-if="activeStep === 2">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" v-if="activeStep === 2">
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { assetService } from '@/api/assetService'

interface Props {
  visible: boolean
  roomData?: Partial<RoomInfo>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const isEdit = computed(() => !!props.roomData?.room_id)

// 表单数据
const form = ref({
  room_name: '',
  location: '',
  building_name: '',
  floor_number: 1,
  status: '正常',
  power_capacity: 0,
  cooling_capacity: 0,
  cabinet_capacity: 0,
  available_cabinets: 0,
  temperature: 22,
  humidity: 45,
  maintenance_contact: '',
  maintenance_phone: '',
  emergency_contact: '',
  emergency_phone: '',
  notes: '',
})

// 监听 roomData 变化，填充表单数据
watch(
  () => props.roomData,
  (newData) => {
    if (newData) {
      // 使用解构赋值来设置表单数据，保留默认值
      Object.assign(form.value, {
        room_name: newData.room_name || '',
        location: newData.location || '',
        building_name: newData.building_name || '',
        floor_number: newData.floor_number || 1,
        status: newData.status || '正常',
        power_capacity: newData.power_capacity || 0,
        cooling_capacity: newData.cooling_capacity || 0,
        cabinet_capacity: newData.cabinet_capacity || 0,
        available_cabinets: newData.available_cabinets || 0,
        temperature: newData.temperature || 22,
        humidity: newData.humidity || 45,
        maintenance_contact: newData.maintenance_contact || '',
        maintenance_phone: newData.maintenance_phone || '',
        emergency_contact: newData.emergency_contact || '',
        emergency_phone: newData.emergency_phone || '',
        notes: newData.notes || '',
      })
    } else {
      // 如果没有数据，重置表单
      Object.assign(form.value, {
        room_name: '',
        location: '',
        building_name: '',
        floor_number: 1,
        status: '正常',
        power_capacity: 0,
        cooling_capacity: 0,
        cabinet_capacity: 0,
        available_cabinets: 0,
        temperature: 22,
        humidity: 45,
        maintenance_contact: '',
        maintenance_phone: '',
        emergency_contact: '',
        emergency_phone: '',
        notes: '',
      })
    }
  },
  { immediate: true },
)

// 表单校验规则
const rules: FormRules = {
  room_name: [{ required: true, message: '请输入机房名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入机房位置', trigger: 'blur' }],
  building_name: [{ required: true, message: '请输入建筑名称', trigger: 'blur' }],
  floor_number: [{ required: true, message: '请输入楼层', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  power_capacity: [{ required: true, message: '请输入额定功率', trigger: 'blur' }],
  cooling_capacity: [{ required: true, message: '请输入制冷能力', trigger: 'blur' }],
  cabinet_capacity: [{ required: true, message: '请输入机柜容量', trigger: 'blur' }],
  available_cabinets: [{ required: true, message: '请输入可用机柜数', trigger: 'blur' }],
  temperature: [{ required: true, message: '请输入温度', trigger: 'blur' }],
  humidity: [{ required: true, message: '请输入湿度', trigger: 'blur' }],
  maintenance_contact: [{ required: true, message: '请输入维护联系人', trigger: 'blur' }],
  maintenance_phone: [{ required: true, message: '请输入维护电话', trigger: 'blur' }],
  emergency_contact: [{ required: true, message: '请输入紧急联系人', trigger: 'blur' }],
  emergency_phone: [{ required: true, message: '请输入紧急电话', trigger: 'blur' }],
}

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
})

// 当前步骤
const activeStep = ref(0)

// 分步验证规则
const stepRules: Record<number, string[]> = {
  0: ['room_name', 'location', 'building_name', 'floor_number', 'temperature', 'humidity'],
  1: ['status', 'power_capacity', 'cooling_capacity', 'cabinet_capacity', 'available_cabinets'],
  2: ['maintenance_contact', 'maintenance_phone', 'emergency_contact', 'emergency_phone'],
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (isEdit.value && props.roomData?.room_id) {
      await assetService.updateRoom({
        ...form.value,
        room_id: props.roomData.room_id,
      })
      ElMessage.success('更新成功')
    } else {
      await assetService.createRoom(form.value)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    emit('success')
  } catch (err) {
    console.error('保存机房失败:', err)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 处理下一步
const handleNext = async () => {
  if (!formRef.value) return

  try {
    // 验证当前步骤的字段
    await Promise.all(
      stepRules[activeStep.value as keyof typeof stepRules].map((field) =>
        formRef.value!.validateField(field),
      ),
    )
    activeStep.value++
  } catch (error) {
    ElMessage.error('请填写完整信息')
    // 验证失败，不进入下一步
  }
}

// 处理上一步
const handlePrev = () => {
  activeStep.value--
}

// 关闭对话框时重置表单和步骤
const handleClose = () => {
  formRef.value?.resetFields()
  activeStep.value = 0
}
</script>

<style scoped lang="scss">
.form-steps {
  margin-bottom: 30px;
  padding: 0 20px;

  :deep(.el-steps) {
    .el-step__head {
      background-color: var(--el-bg-color);
    }

    .el-step__line {
      background-color: var(--el-border-color-lighter);
      height: 2px;
      top: 16px;

      &-inner {
        border: none;
        background-image: linear-gradient(
          90deg,
          var(--el-color-primary) 0%,
          var(--el-color-primary) 100%
        );
        transition: transform 0.3s;
      }
    }

    .el-step.is-success {
      .el-step__line {
        background-color: var(--el-border-color-lighter);
      }

      .el-step__icon {
        color: #fff;
        border-color: var(--el-color-primary);
        background-color: var(--el-color-primary);
      }

      .el-step__title {
        color: var(--el-color-primary);
      }
    }

    .el-step__icon {
      width: 32px;
      height: 32px;
      font-size: 16px;
      border: 2px solid var(--el-border-color);
      transition: all 0.3s;

      &.is-text .el-step__icon__inner {
        font-weight: normal;
        font-size: 14px;
        line-height: 28px;
      }
    }

    .el-step.is-process {
      .el-step__icon {
        border-color: var(--el-color-primary);
      }

      .el-step__title {
        color: var(--el-color-primary);
      }
    }

    .el-step__title {
      font-size: 14px;
      line-height: 32px;
      margin-top: 8px;
      color: var(--el-text-color-regular);

      &.is-wait {
        color: var(--el-text-color-secondary);
      }
    }
  }
}

.room-form {
  padding: 0 20px;

  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 16px;

    .el-form-item {
      flex: 1;
      margin-bottom: 0;
      min-width: 0;

      &:last-child {
        margin-bottom: 0;
      }

      :deep(.el-form-item__label) {
        padding-right: 12px;
        font-weight: normal;
        color: var(--el-text-color-regular);
        white-space: nowrap;
        display: flex;
        align-items: center;

        &::before {
          content: '';
          flex: 0 0 auto;
          width: 8px;
        }

        span {
          flex: 1;
          text-align: justify;
          text-align-last: justify;
          letter-spacing: 1px;
        }

        &::after {
          content: ':';
          flex: 0 0 auto;
          width: 8px;
          text-align: center;
        }
      }

      :deep(.el-form-item__content) {
        flex: 1;
        min-width: 0;
        margin-left: 0 !important;
      }

      :deep(.el-input__wrapper),
      :deep(.el-select),
      :deep(.el-textarea__wrapper) {
        width: 100%;
        box-shadow: 0 0 0 1px var(--el-border-color) inset;

        &:hover {
          box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
      }

      :deep(.number-input) {
        width: 100%;

        .el-input__wrapper {
          padding-right: 11px;
          height: 32px;
          line-height: 32px;
          background: none;
        }

        .el-input__inner {
          text-align: left;
          padding-right: 0;
          height: 32px;
          line-height: 32px;
          background: none;
        }

        .el-input-number__decrease,
        .el-input-number__increase {
          display: none;
        }

        .el-input__wrapper {
          padding: 0 11px;
          box-shadow: 0 0 0 1px var(--el-border-color) inset;

          &:hover {
            box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
          }

          &.is-focus {
            box-shadow: 0 0 0 1px var(--el-color-primary) inset;
          }
        }
      }

      :deep(.el-select) {
        width: 100%;

        .el-input {
          width: 100%;
        }
      }
    }
  }

  > .el-form-item {
    margin-bottom: 16px;

    :deep(.el-textarea__wrapper) {
      padding: 8px 11px;
    }
  }
}

.dialog-footer {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  border-top: 1px solid var(--el-border-color-lighter);

  :deep(.el-button) {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 8px 20px;
    height: 32px;

    span {
      line-height: 1;
    }
  }
}
</style>
